import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';
import rateLimit from 'express-rate-limit';
import { testConnection } from 'common/src/config/database';
import { initializeDatabase } from 'common/src/config/initDatabase';
import userRoutes from './routes/userRoutes';
import wordRoutes from './routes/wordRoutes';
import logger from './config/logger';
import { errorHandler } from './middleware/errorHandler';

// 加载环境变量
dotenv.config();

// 增加事件监听器限制
process.setMaxListeners(20);

const app = express();
const port = process.env.MINIPROGRAM_API_PORT || 3001;

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100 // 限制每个IP 15分钟内最多100个请求
});

// 中间件
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(limiter);

// 请求日志
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.url}`);
  next();
});

// 根路由
app.get('/', (req, res) => {
  res.json({
    message: '英语学习小程序后端API服务',
    version: '1.0.0',
    endpoints: {
      users: '/api/users',
      words: '/api/words'
    }
  });
});

// 路由
app.use('/api', userRoutes);
app.use('/api', wordRoutes);

// 错误处理中间件
app.use(errorHandler);

// 优雅退出
const gracefulShutdown = async () => {
  logger.info('正在关闭服务器...');
  process.exit(0);
};

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
  logger.error('未捕获的异常:', error);
  gracefulShutdown();
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('未处理的Promise拒绝:', reason);
});

// 处理进程信号
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接
    const isConnected = await testConnection();
    if (!isConnected) {
      throw new Error('数据库连接失败');
    }
    
    // 初始化数据库表
    await initializeDatabase();
    
    const server = app.listen(port, () => {
      logger.info(`小程序后端服务器运行在 http://localhost:${port}`);
    });

    // 处理服务器错误
    server.on('error', (error) => {
      logger.error('服务器错误:', error);
      gracefulShutdown();
    });
  } catch (error) {
    logger.error('服务器启动失败:', error);
    process.exit(1);
  }
};

startServer(); 